//
//  UserFeedbackControllerViewController.m
//  CoolTennisBall
//
//  Created by Coollang on 16/11/28.
//  Copyright © 2016年 CoolLang. All rights reserved.
//

#import "UserFeedbackControllerViewController.h"
#import "BRPlaceholderTextView.h"
#import "TZImagePickerController.h"
#import <Photos/Photos.h>
#import <AssetsLibrary/AssetsLibrary.h>
#import "TZImageManager.h"
#import "UIView+CustomAnimation.h"
#import "UIView+Frame.h"
#import "MyNavigationViewController.h"
#import "Masonry.h"

@interface UserFeedbackControllerViewController ()<TZImagePickerControllerDelegate,UICollectionViewDelegate, UICollectionViewDataSource,UITextViewDelegate,UIAlertViewDelegate,UIActionSheetDelegate,UITextViewDelegate,UITextFieldDelegate>

@property (weak, nonatomic) IBOutlet BRPlaceholderTextView *textView;
@property (weak, nonatomic) IBOutlet UICollectionView *collectionView;
@property (weak, nonatomic) IBOutlet UICollectionViewFlowLayout *flowLayout;
@property (weak, nonatomic) IBOutlet UIView *emailSuperView;
@property (weak, nonatomic) IBOutlet FUITextField *textField;
/** 选择的图片 */
@property (nonatomic, strong) NSMutableArray *selectedPhotos;
@property (weak, nonatomic) IBOutlet UIBarButtonItem *sendItem;

@property (weak, nonatomic) IBOutlet UIScrollView *scrollView;

@end

@implementation UserFeedbackControllerViewController {
     NSMutableArray *_selectedAssets;
    BOOL _isSelectOriginalPhoto; // 是否是原图
}
- (void)viewDidLoad {
    [super viewDidLoad];
    _selectedAssets = [NSMutableArray array];
    self.selectedPhotos = [NSMutableArray array];
    
    [self configureNav];
    
    [self configuerLocalizedAndUI];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardFrameChange:) name:UIKeyboardWillChangeFrameNotification object:nil];
}

- (void)configureNav{
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"sport_icon_blackbackArrow"] style:UIBarButtonItemStylePlain target:self action:@selector(back)];
}

- (void)back{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
#pragma mark - 发送反馈
- (IBAction)sendBtnClick:(id)sender {
    
    [self.textView resignFirstResponder];
    [self.textField resignFirstResponder];
    
    if (self.textField.text.length > 0) {
        if (![self verifyEmail:self.textField.text]) {
            FUIAlertView *alertView = [[FUIAlertView alloc] initWithTitle:NSLocalizedString(@"Reminder", nil) message:NSLocalizedString(@"Please enter a valid email address", nil) delegate:nil cancelButtonTitle:NSLocalizedString(@"OK", nil) otherButtonTitles:nil, nil];
            [alertView customizeAppearance];
            [alertView show];
            return;
        }
    }
        
    if (self.textView.text.length > 0 || self.selectedPhotos.count > 0) {
        // 发送反馈
        [YFUserApi feedbackWithImages:self.selectedPhotos email:self.textField.text content:self.textView.text complete:^(NSError *error) {
            [MBProgressHUD hideHUDForView:self.view animated:YES];
            if (error == nil) {
                // 跳转到反馈成功界面
                [self sendSuccessCoverView];
            }else {
                if ([YFCheckNetworkStatus shareInstance].networkStatus == AFNetworkReachabilityStatusNotReachable) {
                    [MBProgressHUD showTextHUDWithMessage:NSLocalizedString(@"Poor network, Try again later", nil) inView:self.view];
                }else {
                    [MBProgressHUD showFailHudInView:self.view message:NSLocalizedString(@"Feedback Fail", nil) afterDelay:1.2];
                }
            }
        }];
    }
}

- (BOOL)verifyEmail:(NSString *)email {
    NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
    NSPredicate *emailVerify = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
    return [emailVerify evaluateWithObject:email];
}

- (void)configuerLocalizedAndUI {
    
    self.sendItem.title = NSLocalizedString(@"Send", @"发送");
    self.title = NSLocalizedString(@"Feedback", "意见反馈");
    self.textField.edgeInsets = UIEdgeInsetsMake(0, 16, 0, 0);
    self.textField.placeholder = NSLocalizedString(@"Can you tall us your email address?", nil); 
    self.flowLayout.itemSize = CGSizeMake(kAutoHei(58), kAutoHei(58));
    self.textField.delegate = self;
    self.textField.enablesReturnKeyAutomatically = YES;
    CGFloat margin = 10;
    self.flowLayout.minimumInteritemSpacing = margin;
    self.flowLayout.minimumLineSpacing = 0;
    CGFloat rightMargin = (kYFScreenWidth - 48 - margin * 3 - self.flowLayout.itemSize.width * 4);
    self.flowLayout.sectionInset = UIEdgeInsetsMake(0, 0, 0, rightMargin);
    
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    self.collectionView.showsVerticalScrollIndicator = NO;
    self.collectionView.bounces = NO;
    
    self.textView.placeholder = NSLocalizedString(@"Please tell us model of your phone and describe your problem.\n\nYou can upload screenshots if it necessary.", nil);
    
    [self.textView setPlaceholderColor:[UIColor colorWithHex:0xaaaaaa]];
    [self.textView setPlaceholderOpacity:0.6];
    self.textView.font = [UIFont systemFontOfSize:14];
    
    [self.collectionView registerClass:[FeedbackImageCell class] forCellWithReuseIdentifier:@"FeedbackImageCell"];
    self.textView.textColor = [UIColor colorWithHex:0x787878];
    self.textView.delegate = self;
    
    self.textView.allowsEditingTextAttributes = YES;
    self.textView.keyboardDismissMode = YES;
    self.textView.alwaysBounceVertical = YES;
    self.textView.enablesReturnKeyAutomatically = YES;
    self.sendItem.enabled = NO;
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textViewDidValueChange:) name:UITextViewTextDidChangeNotification object:nil];
}

#pragma mark - 处理输入框
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    
    if (self.selectedPhotos.count > 0 || self.textView.text.length >= 1) {
        [self sendBtnClick:nil];
    }
    return YES;
}
// 监听用户的Ruturn时间
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{
    
    if ([text isEqualToString:@"\n"]){
        [self.textView resignFirstResponder];
        [self.textField becomeFirstResponder];
        return NO;
    }
    return YES;
}

- (void)textViewDidValueChange:(NSNotification *)note {
    
    if (self.selectedPhotos.count > 0 || self.textView.text.length >= 1) {
        self.sendItem.enabled = YES;
    }else {
        self.sendItem.enabled = NO;
    }
}
- (void)keyboardFrameChange:(NSNotification *)note {
    NSValue *endValue=note.userInfo[UIKeyboardFrameEndUserInfoKey];
    CGRect keyFrame = [endValue CGRectValue];
//    NSLog(@"%@ -- %@",NSStringFromCGRect(keyFrame),NSStringFromCGRect(self.emailSuperView.frame));
    CGFloat offsetY = CGRectGetMaxY(self.emailSuperView.frame) - (keyFrame.origin.y - 64);
    
    if (offsetY > 0) {
        self.scrollView.contentSize = CGSizeMake(kYFScreenWidth, self.scrollView.bounds.size.height + offsetY + 20);
        if (self.textField.isFirstResponder) {
            self.scrollView.contentOffset = CGPointMake(0, (offsetY + 10));
        }else {
            self.scrollView.contentOffset = CGPointMake(0, 0);
        }
    }
}

#pragma mark -MyNavigationViewControllerDelegate
- (BOOL)controllerWillPopHandler {
    return YES;
}

#pragma mark - UICollectionViewDelegate&UICollectionViewDataSource
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    if (self.selectedPhotos.count < 4) {
        return self.selectedPhotos.count + 1;
    }else {
        return self.selectedPhotos.count;
    }
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    FeedbackImageCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"FeedbackImageCell" forIndexPath:indexPath];
    if (indexPath.row == self.selectedPhotos.count && self.selectedPhotos.count <4) {
        cell.imageView.image = [UIImage imageNamed:@"user_addImage"];
    }else {
        cell.imageView.image = self.selectedPhotos[indexPath.row];
    }
    return cell;
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.row == self.selectedPhotos.count && self.selectedPhotos.count <4) {
        [self pushImagePickerController];
    }else {
        [self showActionAlertViewWith:indexPath];
    }
}

#pragma mark - 获取照片
- (void)pushImagePickerController {
   
    TZImagePickerController *imagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:4 columnNumber:4 delegate:self pushPhotoPickerVc:YES];
#pragma mark - 四类个性化设置，这些参数都可以不传，此时会走默认设置
    imagePickerVc.isSelectOriginalPhoto = YES;
    
    imagePickerVc.selectedAssets = _selectedAssets; // 目前已经选中的图片数组
    imagePickerVc.allowTakePicture = YES; // 在内部显示拍照按钮

    // 3. 设置是否可以选择视频/图片/原图
    imagePickerVc.allowPickingVideo = NO;
    imagePickerVc.allowPickingImage = YES;
    imagePickerVc.allowPickingOriginalPhoto = YES;
    
    // 4. 照片排列按修改时间升序
    imagePickerVc.sortAscendingByModificationDate = YES;
    
#pragma mark - 到这里为止
    // 你可以通过block或者代理，来得到用户选择的照片.
    __weak typeof(self) weakSelf = self;
    [imagePickerVc setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
        weakSelf.selectedPhotos = [NSMutableArray arrayWithArray:photos];
         _selectedAssets = [NSMutableArray arrayWithArray:assets];
        [weakSelf.collectionView reloadData];
        if (weakSelf.selectedPhotos.count > 0 || weakSelf.textView.text.length >= 1) {
            weakSelf.sendItem.enabled = YES;
        }else {
            weakSelf.sendItem.enabled = NO;
        }
    }];
    
    imagePickerVc.navigationBar.tintColor = self.navigationController.navigationBar.tintColor;
    imagePickerVc.navigationBar.barTintColor = self.navigationController.navigationBar.barTintColor;    [imagePickerVc.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName: [UIColor whiteColor],
                                                         NSFontAttributeName: [UIFont systemFontOfSize:20.0f]
                                                          }];
    imagePickerVc.navigationBar.alpha = 1.0;
    [self presentViewController:imagePickerVc animated:YES completion:nil];
}
- (void)showActionAlertViewWith:(NSIndexPath *)indexPath {
    
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    
    UIAlertAction *originalAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"Preview", @"预览") style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        // preview photos or video / 预览照片或者视频
        [self priviewSeletePhoto:indexPath];
    }];
    
    UIAlertAction *deleteAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"Delete", @"删除") style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self deleteSeleteImageAtIndex:indexPath.row];
    }];
    
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"Cancel", @"取消") style:UIAlertActionStyleCancel handler:nil];
    
    
    [alertController addAction:originalAction];
    [alertController addAction:deleteAction];
    [alertController addAction:cancelAction];
    
    [self presentViewController:alertController animated:YES completion:nil];
    
}
 // preview photos or video / 预览照片
- (void)priviewSeletePhoto:(NSIndexPath *)indexPath {
    id asset = _selectedAssets[indexPath.row];
    BOOL isVideo = NO;
    if ([asset isKindOfClass:[PHAsset class]]) {
        PHAsset *phAsset = asset;
        isVideo = phAsset.mediaType == PHAssetMediaTypeVideo;
    } else if ([asset isKindOfClass:[ALAsset class]]) {
        ALAsset *alAsset = asset;
        isVideo = [[alAsset valueForProperty:ALAssetPropertyType] isEqualToString:ALAssetTypeVideo];
    }
    if (!isVideo) {
        // preview photos / 预览照片
        TZImagePickerController *imagePickerVc = [[TZImagePickerController alloc] initWithSelectedAssets:_selectedAssets selectedPhotos:_selectedPhotos index:indexPath.row];
        imagePickerVc.maxImagesCount = 4;
        imagePickerVc.allowPickingOriginalPhoto = NO;
        imagePickerVc.isSelectOriginalPhoto = NO;
        [imagePickerVc setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
            _selectedPhotos = [NSMutableArray arrayWithArray:photos];
            _selectedAssets = [NSMutableArray arrayWithArray:assets];
            _isSelectOriginalPhoto = isSelectOriginalPhoto;
            [_collectionView reloadData];
        }];
        [self presentViewController:imagePickerVc animated:YES completion:nil];
    }
}
- (void)deleteSeleteImageAtIndex:(NSInteger)index {
    [self.selectedPhotos removeObjectAtIndex:index];
    [_selectedAssets removeObjectAtIndex:index];
    [self.collectionView reloadData];
    
    if (self.selectedPhotos.count > 0 || self.textView.text.length >= 1) {
        self.sendItem.enabled = YES;
    }else {
        self.sendItem.enabled = NO;
    }
}

#pragma mark - 完成界面
- (void)sendSuccessCoverView {
    
    UIView *successView = [[UIView alloc] initWithFrame:CGRectMake(kYFScreenWidth, 0, kYFScreenWidth, kYFScreenHeight - 64)];
    successView.backgroundColor = [UIColor colorWithHex:0xf3f3f3];
    [self.view addSubview:successView];
    
    UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"user_icon_ smile"]];
    [imageView sizeToFit];
    [successView addSubview:imageView];
    [imageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(successView);
        make.top.equalTo(successView).offset(kAutoHei(67));
    }];
    
    
    UILabel *redLabel = [[UILabel alloc] init];
    redLabel.textColor = [UIColor colorWithHex:0xdf4655];
    redLabel.font = [UIFont boldSystemFontOfSize:22];
    redLabel.text = NSLocalizedString(@"Thank you for your feedback!", nil);
    redLabel.textAlignment = NSTextAlignmentCenter;
    [successView addSubview:redLabel];
    
    [redLabel sizeToFit];
    [redLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(successView);
        make.top.equalTo(imageView.mas_bottom).offset(kAutoHei(38));
    }];
    
    UILabel *blackLabrl = [[UILabel alloc]init];
    blackLabrl.text = NSLocalizedString(@"We will solve the problem and contact\nwith you as soon as possble", nil);
    blackLabrl.numberOfLines = 0;
    blackLabrl.textAlignment = NSTextAlignmentCenter;
    blackLabrl.textColor = [UIColor colorWithHex:0xaaaaaa];
    blackLabrl.font = [UIFont systemFontOfSize:16];
    [blackLabrl sizeToFit];
    [successView addSubview:blackLabrl];
    
    [blackLabrl mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(successView).offset(20);
        make.right.equalTo(successView).offset(-20);
        make.top.equalTo(redLabel.mas_bottom).offset(kAutoHei(20));
    }];
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] init];
    
    [UIView animateWithDuration:0.5 animations:^{
        successView.x = 0;
    } completion:^(BOOL finished) {
    }];
}



@end

@implementation FeedbackImageCell

- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        self.backgroundColor = [UIColor whiteColor];
        self.imageView = [[UIImageView alloc] init];
        _imageView.backgroundColor = [UIColor colorWithWhite:1.000 alpha:0.500];
        _imageView.contentMode = UIViewContentModeScaleAspectFill;
        [self addSubview:_imageView];
         self.clipsToBounds = YES;
    }
    return self;
}

- (void)layoutSubviews {
    [super layoutSubviews];
    _imageView.frame = self.bounds;
}

@end
